#include<iostream>
#include<cassert>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

#define MAX 1024

using namespace std;


int  main()
{
  //建立管道
  int pipefd[2]={0};
  int n=pipe(pipefd);
  assert(n==0);
  (void)n;

  cout<<"pipefd[0]："<<pipefd[0]<<",pipefd[1]"<<pipefd[1]<<endl;

  //创建子进程
  pid_t id=fork();
  if(id<0)
  {
    perror("fork");
    return 1;
  }

  if(id==0)
  {
    close(pipefd[0]);//关闭读，只向管道写

    int cnt=10;
    while(cnt--)
    {
      char message[MAX];
      snprintf(message,sizeof(message),"hello father,i am child,pid:%d,cnt:%d",getpid(),cnt);
      write(pipefd[1],message,strlen(message));
      sleep(1);
    }
    cout<<"child close w"<<endl;
    exit(0);
  }
  close(pipefd[1]);
  //关闭写
  char buffer[MAX];
  while(1)
  {
    sleep(1);
    ssize_t n=read(pipefd[0],buffer,sizeof(buffer)-1);
    if(n>0)
    {
      buffer[n]=0;
       cout << getpid() << ", " << "child say: " << buffer << " to me!" << endl;
    }
 else if(n == 0) { cout << "child quit, me too !" << endl; break; }
        cout << "father return val(n): " << n << endl;
        sleep(1);
}
    cout << "read point close"<< endl;
    close(pipefd[0]);

    sleep(5);
    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if (rid == id)
    {
        cout << "wait success, child exit sig: " << (status&0x7F) << endl;
    }
    return 0;
        

}
